﻿using AutoMapper;
using DeZhen.DataCollection.IRepository.DataSourceSetting;
using DeZhen.DataCollection.IService.DataSourceSetting;
using DeZhen.DataCollection.Model.Common;
using DeZhen.DataCollection.Model.DTO.DataSourceSettings;
using DeZhen.DataCollection.Model.Entities;
using SqlSugar;
using Yitter.IdGenerator;

namespace DeZhen.DataCollection.Service.DataSourceSetting
{
    public class DataSourceSettingsSerevice : IDataSourceSettingsSerevice
    {
        private readonly IDataSourceSettingsRepository _repository;
        private readonly IMapper _mapper;
        public DataSourceSettingsSerevice(IDataSourceSettingsRepository repository, IMapper mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }

        public async Task<PageResult<DataSourceSettingsDTO>> GetListToPageAsync(QueryDataSourceSettings param)
        {
            var items = (await _repository.GetListAsync())
                         .WhereIF(!string.IsNullOrEmpty(param.DataSourceName), x => x.SourceName.Contains(param.DataSourceName))
                         .OrderByDescending(x => x.CreateTime)
                         .Skip((param.Page - 1) * param.PageSize)
                         .Take(param.PageSize)
                         .ToList();
            // 使用 AutoMapper 将实体列表转换为 DTO 列表
            var result = _mapper.Map<List<DataSourceSettingsDTO>>(items);

            return new PageResult<DataSourceSettingsDTO>
            {
                TotalCount = result.Count,
                Items = result
            };
        }

        public async Task<List<DataSourceSettingsDropDownDTO>> GetDropDownListAsync() 
        {
            var modelList = await _repository.GetListAsync();

            return _mapper.Map<List<DataSourceSettingsDropDownDTO>>(modelList);
        }
        public async Task<DataSourceSettingsDTO> GetSettingsByIdAsync(long id)
        {
            var model = await _repository.GetByIdAsync(id);

            return _mapper.Map<DataSourceSettingsDTO>(model);
        }

        public async Task<bool> AddAsync(DataSourceSettingsAdd input)
        {
            var queryResult = (await _repository.GetListAsync())
                                .WhereIF(!string.IsNullOrEmpty(input.SourceName), x => x.SourceName.Equals(input.SourceName));
            // 检查数据源名称是否已存在
            if (queryResult.Any())
            {
                throw new Exception("数据源名称已存在");
            }

            var model = _mapper.Map<DataSourceSettingsAdd, DataSourceSettings>(input);
            model.Id = YitIdHelper.NextId();
            model.CreateTime = DateTime.Now;

            return await _repository.CreateAsync(model);
        }

        public async Task<bool> UpdateAsync(DataSourceSettingsEdit input)
        {
            var model = await _repository.GetByIdAsync(input.Id);
            if (model == null)
            {
                throw new Exception("数据源设置信息为空");
            }

            var result = _mapper.Map(input, model);

            return await _repository.UpdateAsync(result);
        }

        public async Task DeleteAsync(long id)
        {
            var model = await _repository.GetByIdAsync(id);
            if (model == null)
            {
                throw new Exception("数据源设置信息为空");
            }

            await _repository.DeleteAsync(id);
        }

        public async Task<bool> TestConnectionAsync(DataSourceSettingsAdd input)
        {
            if (input.SourceType == null)
                throw new Exception("数据源类型不能为空");

            string connStr;
            SqlSugar.DbType dbType = input.SourceType.Value;

            switch (dbType)
            {
                case SqlSugar.DbType.SqlServer:
                    connStr = $"Server={input.DatabaseUrl};Database={input.DatabaseName};User ID={input.LoginUser};Password={input.LoginPassword};TrustServerCertificate=true;";
                    break;
                case SqlSugar.DbType.MySql:
                    connStr = $"Server={input.DatabaseUrl};Port={input.Port};Database={input.DatabaseName};Uid={input.LoginUser};Pwd={input.LoginPassword};";
                    break;
                case SqlSugar.DbType.Oracle:
                    connStr = $"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST={input.DatabaseUrl})(PORT={input.Port})))(CONNECT_DATA=(SERVICE_NAME={input.DatabaseName})));User Id={input.LoginUser};Password={input.LoginPassword};";
                    break;
                default:
                    throw new NotSupportedException($"暂不支持的数据库类型: {dbType}");
            }

            var config = new ConnectionConfig
            {
                ConnectionString = connStr,
                DbType = dbType,
                IsAutoCloseConnection = true
            };

            try
            {
                using var db = new SqlSugarClient(config);
                // 执行一个简单的SQL来测试连接
                await db.Ado.OpenAsync();
                await db.Ado.CloseAsync();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }

}
